﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using System.IO;
using System.Reflection;
namespace generate_wmi_classes
{
    class Program
    {
        static string outputDir = @"F:\workspace\hyper-v-mgmt\wave3\hypervmgmtlib\wmi_root_virtualization";
        static string server = "vmshark12";

        //public static bool GetStronglyTypedClassCode(ManagementClass thisCls, CodeLanguage lang, string filePath, string classNamespace)
        //{
        //    var asm = Assembly.LoadWithPartialName("System.Management");
        //    var type = asm.GetType("System.Management.ManagementClassGenerator");
        //    var obj = Activator.CreateInstance(type, thisCls);
        //    object ret = type
        //        .GetMethod("GenerateCode", new Type[] { typeof(CodeLanguage), typeof(string), typeof(string) })
        //        .Invoke(obj, new object[] { lang, filePath, classNamespace });
        //    return (bool)ret;
        //}

        static void generateCode(ManagementClass cls)
        {
            string clsName = cls.Path.ClassName;
            string outputFilePath = Path.Combine(outputDir, clsName + ".cs");
            //GetStronglyTypedClassCode(cls, CodeLanguage.CSharp, outputFilePath, "wmi.root.virtualization");
            string ns = "wmi.root.virtualization";
            if (clsName.StartsWith("CIM_"))
                ns += ".cim";
            else if (clsName.StartsWith("Msvm_"))
                ns += ".msvm";
            cls.GetStronglyTypedClassCode(CodeLanguage.CSharp, outputFilePath, ns);
        }

        static List<ManagementClass> GetDecendantClasses(ManagementClass cls)
        {
            var decendants = new List<ManagementClass>();

            foreach (ManagementClass immediateSubCls in cls.GetSubclasses())
            {
                decendants.Add(immediateSubCls);
                decendants.AddRange(GetDecendantClasses(immediateSubCls));
            }
            return decendants;
        }

        static void Main(string[] args)
        {
            var nsCls = new ManagementClass(new ManagementPath(string.Format(@"\\{0}\root\virtualization", server)));
            foreach (var cls in GetDecendantClasses(nsCls))
            {
                if (cls.ClassPath.ClassName.StartsWith("_")) continue;
                Console.WriteLine(cls.ClassPath.ClassName);
                generateCode(cls);
            }
        }
    }
}
